/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: mirac
 * Date: 2025-08-30
 * Time: 13:20
 */
public class Sort {

    //冒泡排序
    public static void bubbleSort(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            boolean flg = false;
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    swap(arr,j,j + 1);
                    flg = true;
                }
            }
            if (!flg) {
                break;
            }
        }
    }

    //交换
    private static void swap(int[] arr,int i,int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    //快速排序
    public static void quickSort(int[] arr) {
        quick(arr,0,arr.length - 1);
    }
    private static void quick(int[] arr,int start,int end) {
        if (start >= end) {
            return;
        }
        int pivot = partition(arr,start,end);

        quick(arr,start,pivot - 1);
        quick(arr,pivot + 1,end);
    }
    //霍尔法
    private static int partitionHoare(int[] arr,int left,int right) {
        int temp = arr[left];
        int tempLeft = left;
        while (left < right) {
            while (left < right && arr[right] >= temp) {
                right--;
            }
            while (left < right && arr[left] <= temp) {
                left++;
            }
            swap(arr,left,right);
        }
        swap(arr,left,tempLeft);
        return left;
    }
    //挖坑法
    private static int partition(int[] arr,int left,int right) {
        int temp = arr[left];
        while (left < right) {
            while (left < right && arr[right] >= temp) {
                right--;
            }
            arr[left] = arr[right];
            while (left < right && arr[left] <= temp) {
                left++;
            }
            arr[right] = arr[left];
        }
        arr[left] = temp;
        return left;
    }
    //前后指针法_写法一
    public static int  partition1(int[] arr,int left,int right) {
        int prev = left;
        int cur = left + 1;
        while (cur <= right) {
            if (arr[cur] < arr[left] && arr[++prev] != arr[cur]) {
                swap(arr,cur,prev);
            }
            cur++;
        }
        swap(arr,prev,left);
        return prev;
    }
    //前后指针法_写法二
    public static int  partition2(int[] arr,int left,int right) {
        int d = left + 1;
        int pivot = arr[left];
        for (int i = left + 1; i <= right; i++) {
            if (arr[i] < pivot) {
                swap(arr,i,d);
                d++;
            }
        }
        swap(arr,d - 1,left);
        return d - 1;
    }
}
